package com.concurrent.controller;


import com.concurrent.model.User;
import com.concurrent.model.UserRole;
import com.concurrent.service.UserService;
import org.apache.ibatis.mapping.ResultMap;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.List;

import static org.apache.shiro.util.ThreadContext.getSubject;

@Controller
public class LoginController {



    @Autowired
    UserService userService;

    /**
     * 跳转到登录页面
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login() {
        if(getSubject() != null && getSubject().isAuthenticated()&&getSubject().getPrincipals().getPrimaryPrincipal() != null){
            return "redirect:/";
        }
            return "login";
    }

    /**
     * 跳转到首页
     */
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index(Model model) {
        User user = (User)SecurityUtils.getSubject().getPrincipal();
        //根据权限，指定返回数据
        List<UserRole> role = userService.selectRoleByUsername(user.getUsername());
        model.addAttribute("roleList",role);
        return "index";
    }
    /**
     * 登陆执行的动作
     *
     * @param username 用户名
     * @param password 密码
     */
    @RequestMapping(value = "/login", method ={RequestMethod.POST} )
    public String login(String username, String password, Model model) {
        // 从SecurityUtils里边创建一个 subject
        Subject subject = SecurityUtils.getSubject();
        // 在认证提交前准备 token（令牌）
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        // 执行认证登陆
        subject.login(token);
        return "redirect:/";
    }
}
